//
//  DLLoginVC.m
//  delongzhitou
//
//  Created by Mr.Wang on 2018/11/22.
//  Copyright © 2018 delongzhitou. All rights reserved.
//

#import "DLLoginVC.h"
#import "DLRegistVC.h"
#import "DLForgetPasswordVC.h"
#import "DLSmsLoginView.h"
#import "DLPasswordLoginView.h"

@interface DLLoginVC ()

@property (nonatomic, strong) DLSmsLoginView *smsLoginView;

@property (nonatomic, strong) DLPasswordLoginView *passwordLoginView;

@property (nonatomic, strong) UILabel *changeLoginTypeLabel;

@property (nonatomic, assign) BOOL isSmsCodeLogin;

@property (nonatomic, copy) NSString *phoneNum;

@property (nonatomic, copy) NSString *verifyCode;

@end

@implementation DLLoginVC

- (void) viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [self setUpNav];
}
- (void) viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.smsLoginView endEditing:YES];
    [self.passwordLoginView endEditing:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isSmsCodeLogin = NO;
    
    [self layoutSubControls];
    // Do any additional setup after loading the view.
}

- (void) layoutSubControls {
    
    UIImageView *imageV = [UIImageView new];
    imageV.frame = CGRectMake(0, 0, self.view.width, self.view.height);
    imageV.backgroundColor = [UIColor whiteColor];
    [self.view addSubview: imageV];
    imageV.userInteractionEnabled = YES;
    
    
    UIImageView *logoImageV = [UIImageView new];
    logoImageV.frame = CGRectMake((kScreenWidth - 100) / 2, kHeightNavigation, 100, 90);
    logoImageV.image = [UIImage imageNamed:@"login_logo"];
    [imageV addSubview:logoImageV];
    
    
    CGFloat loginViewWidth = kAutoWidth(287);
    CGFloat loginViewHeight = 100;
    CGFloat leftMargin = kAutoWidth(44);
    
    DLSmsLoginView *smsLoginView = [[DLSmsLoginView alloc] initWithFrame:CGRectMake(leftMargin, logoImageV.bottom + 60, loginViewWidth, loginViewHeight)];
    smsLoginView.backgroundColor = [UIColor whiteColor];
    [imageV addSubview:smsLoginView];
    smsLoginView.alpha = 0;
    self.smsLoginView = smsLoginView;
    
    
    DLPasswordLoginView *passwordLoginView = [[DLPasswordLoginView alloc] initWithFrame:CGRectMake(smsLoginView.left, smsLoginView.top, loginViewWidth, loginViewHeight)];
    passwordLoginView.backgroundColor = [UIColor whiteColor];
    [imageV addSubview:passwordLoginView];
    self.passwordLoginView = passwordLoginView;
    
    
    UIButton *loginBtn = [UIButton buttonWithType:0];
    loginBtn.frame = CGRectMake((kScreenWidth - 170) / 2, logoImageV.bottom + 211, 170, 39);
    loginBtn.layer.cornerRadius = 19.5;
    loginBtn.clipsToBounds = YES;
    loginBtn.adjustsImageWhenHighlighted = NO;
    [loginBtn setBackgroundImage:[UIImage imageNamed:@"loginbtnbg"] forState:UIControlStateNormal];
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    loginBtn.titleLabel.font = kSystemFont(18);
    [imageV addSubview:loginBtn];
    [loginBtn addTarget:self action:@selector(loginBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *forgetPasswordLabel = [UILabel new];
    forgetPasswordLabel.frame = CGRectMake(leftMargin, loginBtn.bottom + 15, loginViewWidth / 2, 20);
    forgetPasswordLabel.userInteractionEnabled = YES;
    forgetPasswordLabel.text = @"忘记密码？";
    forgetPasswordLabel.textAlignment = NSTextAlignmentLeft;
    forgetPasswordLabel.textColor = kDLNormalGrayColor;
    forgetPasswordLabel.font = kSystemFont(14);
    [imageV addSubview:forgetPasswordLabel];
    
    
    UITapGestureRecognizer *forgetPasswordLabelTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(forgetPasswordLabelTap:)];
    [forgetPasswordLabel addGestureRecognizer:forgetPasswordLabelTapGes];
    
    
    UILabel *changeLoginTypeLabel = [UILabel new];
    changeLoginTypeLabel.frame = CGRectMake(forgetPasswordLabel.right, forgetPasswordLabel.top, loginViewWidth / 2, 20);
    changeLoginTypeLabel.userInteractionEnabled = YES;
    changeLoginTypeLabel.text = @"验证码登录";
    changeLoginTypeLabel.textAlignment = NSTextAlignmentRight;
    changeLoginTypeLabel.textColor = kDLNormalBlackColor;
    changeLoginTypeLabel.font = kSystemFont(14);
    [imageV addSubview:changeLoginTypeLabel];
    self.changeLoginTypeLabel = changeLoginTypeLabel;
    
    UITapGestureRecognizer *changeLoginTypeLabelTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeLoginTypeLabelTap:)];
    [changeLoginTypeLabel addGestureRecognizer:changeLoginTypeLabelTapGes];
    
    UILabel *registlabel = [UILabel new];
    registlabel.userInteractionEnabled = YES;
    registlabel.textAlignment = NSTextAlignmentCenter;
    registlabel.frame = CGRectMake((kScreenWidth - 200) / 2, kScreenSafeAreaHeight - 50, 200, 20);
    registlabel.text = @"还没有账号？去注册";
    registlabel.textColor = kDLNormalBlackColor;
    registlabel.font = kSystemFont(14);
    [imageV addSubview:registlabel];
    
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:registlabel.text];
    [attrStr addAttribute:NSForegroundColorAttributeName
                    value:kDLBtnNormalBgColor
                    range:NSMakeRange(6, 3)];
    registlabel.attributedText = attrStr;
    
    UITapGestureRecognizer *registlabelTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(registlabelTap:)];
    [registlabel addGestureRecognizer:registlabelTapGes];
    
    
}

- (void) registlabelTap:(UITapGestureRecognizer *)tapGes {
    
    //注册
    DLRegistVC *rVC = [DLRegistVC new];
    [self.navigationController pushViewController:rVC animated:YES];
}

- (void) loginBtnClick:(UIButton *)btn {
    
    if (self.isSmsCodeLogin) {
        self.phoneNum = self.smsLoginView.phoneTF.text;
        self.verifyCode = self.smsLoginView.smscodeTF.text;
        
    } else {
        self.phoneNum = self.passwordLoginView.phoneTF.text;
        self.verifyCode = self.passwordLoginView.passwordTF.text;
        
    }
    
    if (self.isSmsCodeLogin) {
        
        if (self.phoneNum.length < 11) {
            
//            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//            hud.labelText = @"请输入正确的手机号";
//            [hud show:YES];
//            [hud hide:YES afterDelay:0.8];
            
            [[UIApplication sharedApplication].keyWindow makeToast:@"请输入正确的手机号" duration:1 position:CSToastPositionCenter];
            
            return;
        }
        
        if (self.verifyCode.length < 4) {
//            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//            hud.labelText = @"请输入正确的验证码";
//            [hud show:YES];
//            [hud hide:YES afterDelay:0.8];
            
            [[UIApplication sharedApplication].keyWindow makeToast:@"请输入正确的验证码" duration:1 position:CSToastPositionCenter];
            return;
        }
    } else {
        
        if (self.phoneNum.length < 11) {
//            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//            hud.labelText = @"请输入正确的手机号";
//            [hud show:YES];
//            [hud hide:YES afterDelay:0.8];
            
            [[UIApplication sharedApplication].keyWindow makeToast:@"请输入正确的手机号" duration:1 position:CSToastPositionCenter];
            return;
        }
        
        if (self.verifyCode.length < 6) {
//            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//            hud.labelText = @"请输入正确的密码";
//            [hud show:YES];
//            [hud hide:YES afterDelay:0.8];
            
            [[UIApplication sharedApplication].keyWindow makeToast:@"请输入正确的密码" duration:1 position:CSToastPositionCenter];
            return;
        }
    }
    
    [self loginAction];
}
- (void) loginAction {
    
    //接口
    NSString *postUrl = self.isSmsCodeLogin ?HTTPLoginBySmsCode:HTTPLoginByPassword;
    
    NSDictionary *postDic;
    if (self.isSmsCodeLogin == YES) {
        
        postDic = @{
                     @"mobile" : self.phoneNum,
                     @"smscode" : self.verifyCode,
                     @"imageCode" : self.smsLoginView.imageVerifyAlertView.smscodeTF.text?:@""
                     };
    } else {
        
        NSString *md5Password = [self.verifyCode md5Hash];
        postDic = @{
                    @"mobile" : self.phoneNum,
                    @"password" : md5Password
                    };
    }
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeAnnularDeterminate;
    hud.labelText = @"登录中···";
    [[DLNetWorkManager shareInstance] requestWithMethod:DLRequestMethodPOST path:postUrl parameters:postDic success:^(id  _Nonnull responseObject) {
        [hud hide:YES];
        if (kRequestSuccess(responseObject)) {
            
//            kShowRequestMsg(kSafeString(responseObject[@"message"]));
            
            [kuserManager saveLoginTokenDict:responseObject[@"result"]];
            [kuserManager analyzeUserDataWithDict:responseObject[@"result"]];
            kuserManager.isLogin = YES;
            
            [self checkUserRiskEvaluationState];
        } else {
            
            kShowRequestMsg(kSafeString(responseObject[@"message"]));
            
        }
    } failure:^(NSError * _Nonnull error) {
        NSLog(@"请求接口失败，错误是：%@", error);
    }];
}
//查询用户是否进行过风险测评
- (void) checkUserRiskEvaluationState {
    
    NSString *postUrl = HTTPCheckUserIsRiskAssessment;
    NSDictionary *postDic = @{
                              };
    [[DLNetWorkManager shareInstance] requestWithMethod:DLRequestMethodPOST path:postUrl parameters:postDic success:^(id  _Nonnull responseObject) {
        if (kRequestSuccess(responseObject)) {
//            kShowRequestMsg(kSafeString(responseObject[@"message"]));
            kuserManager.userInfoModel.isRiskEvaluation = YES;
        } else {
//            kShowRequestMsg(kSafeString(responseObject[@"message"]));
            kuserManager.userInfoModel.isRiskEvaluation = NO;
        }
        [self dismissViewControllerAnimated:YES completion:^{
            
            
        }];
    } failure:^(NSError * _Nonnull error) {
        NSLog(@"请求接口失败，错误是：%@", error);
        kuserManager.userInfoModel.isRiskEvaluation = NO;
        [self dismissViewControllerAnimated:YES completion:^{
            
            
        }];
    }];
}

- (void) forgetPasswordLabelTap:(UITapGestureRecognizer *)tapGes {
    DLForgetPasswordVC *fpvc = [DLForgetPasswordVC new];
    [self.navigationController pushViewController:fpvc animated:YES];
}

- (void) changeLoginTypeLabelTap:(UITapGestureRecognizer *)tapGes {
    
    self.isSmsCodeLogin = !self.isSmsCodeLogin;
    
    if (self.isSmsCodeLogin) {
        self.changeLoginTypeLabel.text = @"密码登录";
        [UIView animateWithDuration:0.3 animations:^{
            self.passwordLoginView.alpha = 0;
            self.smsLoginView.alpha = 1;
        }];
    } else {
        self.changeLoginTypeLabel.text = @"验证码登录";
        [UIView animateWithDuration:0.3 animations:^{
            self.smsLoginView.alpha = 0;
            self.passwordLoginView.alpha = 1;
        }];
    }
}


- (void) setUpNav {
    
    self.hiddenNavigationBackground = YES;
    self.hiddenNavigationBottomLine = YES;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
